import cookies from "vue-cookies";
import store from 'store'

export default{
  namespaced:true,
  state:{
    userInfo:null,
    showUnlogin:true,
  },
  mutations:{
    save_userInfo(state,userInfo){
      state.userInfo = userInfo
      cookies.set('userInfo',JSON.stringify(userInfo), 7*24*3600)
      //sessionStorage.setItem('userInfo',JSON.stringify(userInfo))
      // console.log('save_userInfo')
      //保存 userInfo时，保存到 account中进行角色权限保存
      this.commit('user/setRoles', userInfo)
    },
    setRoles(state, userInfo){
      // 角色权限保存操作
      // console.log('user-setRoles' ,state,userInfo)
      // 此处使用假数据进行测试
      // let roles = [{
      //   id: '/device/account',                                  
      //   operation: ['add', 'delete', 'edit', 'open'] 
      // }]
      let roles = userInfo.auths?userInfo.auths:[]
      console.log(roles)
      store.commit('account/setRoles', roles)
      store.commit('account/setPermissions', roles)
      // this.commit('account/setRoles', roles)
    },
    out_login(state){
      state.userInfo = null
      cookies.remove('userInfo')
      // sessionStorage.clear('userInfo')
    },
    changeSetShow(state,e){
      state.userInfo.member.setshow =  e
      cookies.set('userInfo',JSON.stringify(state.userInfo), 7*24*3600)
      //sessionStorage.setItem('userInfo',JSON.stringify(state.userInfo))
    },
    setShowUnlogin(state,e){
      state.showUnlogin = e
    }
  },
  actions:{
    check_userInfo(context){
      return new Promise((resolve) => {
        let userInfo = cookies.get('userInfo')
        //let userInfo = sessionStorage.getItem('userInfo');
        if (context.state.userInfo == null) {
          // console.log('userInfo', userInfo);
          if (userInfo) {
            // cookie1中存在 userInfo，判断过期时间
            let now_time = Math.floor((new Date()).valueOf() / 1000)
            if (userInfo.expiretime < now_time) {
              resolve(false)
            } else {
              context.state.userInfo = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo;
            }
          }else{
            resolve(false)
          }
        }
        resolve(true);
      });
    },
  }
}